package httpapi

import (
	"fmt"
	"strconv"

	"away.wei/minidevpos/db"
	"away.wei/minidevpos/model"
	"github.com/gin-gonic/gin"
)

type ServerApi struct{}

// @Tags Server
// @Summary 添加
// @Security ApiKeyAuth
// @Param data body db.Server  true " "
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /server [post]
func (s *ServerApi) Create(c *gin.Context) {
	var config db.Server
	_ = c.ShouldBindJSON(&config)
	if err := serverRep.Create(config); err != nil {
		FailWithMessage(err.Error(), c)
	} else {
		OkWithMessage("创建成功", c)
	}
}

// @Tags Server
// @Summary 删除
// @Security ApiKeyAuth
// @Param ids body []int true "编号"
// @Router /server [delete]
func (s *ServerApi) Delete(c *gin.Context) {
	var ids []int
	_ = c.ShouldBindJSON(&ids)
	if err := serverRep.Delete(ids); err != nil {
		FailWithMessage(err.Error(), c)
	} else {
		OkWithMessage("删除成功", c)
	}
}

// @Tags Server
// @Summary 更新
// @Security ApiKeyAuth
// @Param data body db.Server  true " "
// @Router /server [put]
func (s *ServerApi) Update(c *gin.Context) {
	var dto db.Server
	_ = c.ShouldBindJSON(&dto)
	if err := serverRep.Update(dto); err != nil {
		FailWithMessage(err.Error(), c)
	} else {
		OkWithMessage("更新成功", c)
	}
}

// @Tags Server
// @Summary 分页查询
// @Security ApiKeyAuth
// @Param data query model.ServerSearch true " "
// @Router /server/getpage [get]
func (s *ServerApi) GetPage(c *gin.Context) {
	var dto model.ServerSearch
	c.ShouldBindQuery(&dto)
	list, total, err := serverRep.GetPage(dto)

	if err != nil {
		FailWithMessage("获取失败", c)
	} else {
		OkWithDetailed(PageResult{
			List:     list,
			Total:    total,
			Page:     dto.Page,
			PageSize: dto.PageSize,
		}, "获取成功", c)
	}
}

// @Tags Server
// @Summary 查询全部
// @Security ApiKeyAuth
// @Router /server/getselectrows [get]
func (s *ServerApi) GetSelectRows(c *gin.Context) {
	list, err := serverRep.GetAll()
	if err != nil {
		FailWithMessage("获取失败", c)
	} else {
		selectRows := make([]model.SelectRows, 0)
		for _, v := range list {
			selectRows = append(selectRows, model.SelectRows{
				Value: v.ID,
				Label: fmt.Sprintf("%s@%s:%s", v.Username, v.IP, strconv.Itoa(v.Port)),
			})
		}
		OkWithDetailed(selectRows, "获取成功", c)
	}
}
